#include "personrepository.h"
#include "person.h"

#include <QFileInfo>
#include <QTextStream>
#include <QStringList>
#include <QDebug>

PersonRepository::PersonRepository()
{
	populateRepository();
}

void PersonRepository::populateRepository()
{
	QFile inputFile( "personRepo.txt" );
	bool ok;

	if( inputFile.open( QIODevice::ReadOnly ) )
	{
		QTextStream input( &inputFile );

		while( !input.atEnd() )
		{
			const QString dataString = input.readLine();
			const QStringList dataStringList = dataString.split( ", ", QString::SkipEmptyParts );

			Person readPersonData;
			readPersonData.setId( dataStringList.value( 0 ).toInt( &ok ) );
			readPersonData.setName( dataStringList.value( 1 ) );

			const QStringList borrowedBooks = dataStringList.value( 2 ).split( " ", QString::SkipEmptyParts );

			QVector<ID> bookList;
			for( int i = 0; i < borrowedBooks.size(); i++ )
			{
				bookList.append( borrowedBooks.value( i ).toInt( &ok ) );
			}
			readPersonData.setBorrowdBooksList( bookList );

			m_personList.append( readPersonData );
		}
	}

	inputFile.close();
}

QVector<Person> PersonRepository::getList() const
{
	return m_personList;
}

void PersonRepository::updateList( const QVector<Person> personList )
{
	m_personList = personList;
}

void PersonRepository::updateDataBase()
{
	QFile inputFile( "personRepo.txt" );

	if( inputFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
	{
		QTextStream output( &inputFile );

		for( int i = 0; i < m_personList.size(); i++ )
		{
			ID personId = m_personList.value( i ).getId();
			QString personName = m_personList.value( i ).getName();
			QVector<ID> bookList = m_personList.value( i ).getBorrowdBooksList();

			output << personId << ", " << personName << ", ";

			for( int j = 0; j < bookList.size(); j++ )
			{
				output << bookList.value( j ) << " ";
			}
			output << "\n";
		}
	}
	else
	{
		qDebug() << "Failed to open personRepository.txt file";
	}

	if( inputFile.isOpen() )
	{
		inputFile.close();
	}
}
